package com.czone.myfacebook;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.czone.myfacebook.MainActivity.MainCallBack;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SlidingDrawer;
import android.widget.TextView;

public class FeedViewFragment extends Fragment implements OnScrollListener {
    private static final String TAG = "FeedViewFragment";

    private View mRootView;
    private View mFooterView;
    private TextView mFooterViewText;
    private ProgressBar mFooterProgressBar;
    private ListView mNewsfeedList;
    private SlidingDrawer mNewsfeedDrawer;
    private NewsfeedListAdapter mAdapter;
    private MainCallBack mFeedViewScrollCallback;

    private FaceBookDataManager mFaceBookDataManager;
    private ArrayList<FaceBookData> mFeedDatas;
    private HashMap<String, ProfileImageData> mProfileImageHash;

    private ArrayList<String> mNewsfeedContent = new ArrayList<String>();

    private ImageView mPrivatePicture;
    private TextView mPrivateName;
    private TextView mPrivateDate;
    private TextView mContentText;
    private ImageView mContentImage;

    private boolean mLoadingState = true;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Define.FEEDVIEWFRAGMENT_ADAPTER_REFRESH:
                    CLog.d(TAG, "mHandler ::  FEEDVIEWFRAGMENT_ADAPTER_REFRESH");
                    if (mHandler.hasMessages(Define.FEEDVIEWFRAGMENT_ADAPTER_REFRESH)) {
                        mHandler.removeMessages(Define.FEEDVIEWFRAGMENT_ADAPTER_REFRESH);
                    }

                    if (mAdapter != null) {
                        mAdapter.notifyDataSetChanged();
                    }
                    break;

                case Define.FEEDVIEWFRAGMENT_LOADING_STATE:
                    CLog.d(TAG, "mHandler ::  FEEDVIEWFRAGMENT_LOADING_STATE");
                    if (mHandler.hasMessages(Define.FEEDVIEWFRAGMENT_LOADING_STATE)) {
                        mHandler.removeMessages(Define.FEEDVIEWFRAGMENT_LOADING_STATE);
                    }

                    if (mFooterViewText != null && mFooterProgressBar != null && getActivity() != null && getActivity().getResources() != null) {
                        if (!mLoadingState && mFooterProgressBar.getVisibility() != View.GONE) {
                            mFooterViewText.setText(getActivity().getResources().getString(R.string.end_list));
                            mFooterProgressBar.setVisibility(View.GONE);
                        } else if (mFooterProgressBar.getVisibility() == View.GONE) {
                            mFooterViewText.setText(getActivity().getResources().getString(R.string.loading));
                            mFooterProgressBar.setVisibility(View.VISIBLE);
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        CLog.i(TAG, "onCreateView Start");

        mRootView = inflater.inflate(R.layout.feedview, container, false);
        mFooterView = inflater.inflate(R.layout.list_footer, null);

        mFooterProgressBar = (ProgressBar) mFooterView.findViewById(R.id.footer_progress);
        mFooterViewText = (TextView) mFooterView.findViewById(R.id.footer_text);

        mNewsfeedList = (ListView) mRootView.findViewById(R.id.newsfeed_list);
        mNewsfeedDrawer = (SlidingDrawer) mRootView.findViewById(R.id.newsfeed_detail);

        // mNewsfeedDrawer.setOnClickListener(new View.OnClickListener() {
        // @Override
        // public void onClick(View v) {
        // mNewsfeedDrawer.animateClose();
        // }
        // });

        mNewsfeedDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {
            @Override
            public void onDrawerClosed() {
                mNewsfeedDrawer.setVisibility(View.GONE);
            }
        });

        mNewsfeedList.setOnScrollListener(this);
        mNewsfeedList.setOnItemClickListener(new ListItemClickListener());
        mNewsfeedList.addFooterView(mFooterView);

        return mRootView;
    }

    private class NewsfeedListAdapter extends BaseAdapter {
        Context mContext;

        NewsfeedListAdapter(Context ctx, int itemLayout) {
            mContext = ctx;
        }

        @Override
        public int getCount() {
            return mNewsfeedContent != null ? mNewsfeedContent.size() : 0;
        }

        @Override
        public String getItem(int position) {
            return mNewsfeedContent != null ? mNewsfeedContent.get(position) : null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            CLog.i(TAG, "getView position = " + position);
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.feedview_item, parent, false);
            }

            ImageView v = (ImageView) convertView.findViewById(R.id.view);
            if (v != null) {
                ProfileImageData pID = mProfileImageHash.get(getFeedDataValue(position, Define.INDEX_FROM_ID));
                CLog.d(TAG, "pID = " + pID + ", position = " + position);

                if (pID != null) {
                    CLog.d(TAG, "pID.getImgView = " + pID.getBitmap());

                    if (pID.getBitmap() == null) {
                        new DownloadImageTask(v, pID).execute(pID.getURL());
                    } else {
                        v.setVisibility(View.VISIBLE);
                        v.setImageBitmap(pID.getBitmap());
                    }
                } else {
                    CLog.i(TAG, "doRequestProfileImage Call, ID = " + getFeedDataValue(position, Define.INDEX_FROM_ID));
                    v.setVisibility(View.INVISIBLE);
                    mFaceBookDataManager.doRequestProfileImage(v, getFeedDataValue(position, Define.INDEX_FROM_ID));
                }
            }

            TextView tv = (TextView) convertView.findViewById(R.id.text);
            if (tv != null) {
                tv.setText(mNewsfeedContent.get(position));
            }

            return convertView;
        }
    }

    /* The click listner for ListView */
    private class ListItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position, view);
        }
    }

    private void selectItem(int position, View view) {
        if (mNewsfeedDrawer == null) {
            CLog.e(TAG, "selectItem() :: mNewsfeedDrawer is null");
            return;
        }

        // if (mNewsfeedDrawer.isOpened()) {
        // mNewsfeedDrawer.animateClose();
        // return;
        // }

        initDetailViews();

        if (mPrivatePicture != null) {
            // privatePicture.setImageResource(R.drawable.test);
            ProfileImageData pID = mProfileImageHash.get(getFeedDataValue(position, Define.INDEX_FROM_ID));
            if (pID != null)
                mPrivatePicture.setImageBitmap(pID.getBitmap());
        }

        if (mPrivateName != null) {
            mPrivateName.setText(getFeedDataValue(position, Define.INDEX_FROM_NAME));
        }

        if (mPrivateDate != null) {
            mPrivateDate.setText(getFeedDataValue(position, Define.INDEX_DATE));
        }

        if (mContentText != null) {
            mContentText.setText(getTitle(position));
        }

        if (mContentImage != null) {
            mContentImage.setVisibility(View.INVISIBLE);

            String imgURL = getFeedDataValue(position, Define.INDEX_PICTURE);
            if (null != imgURL) {
                mContentImage.setVisibility(View.VISIBLE);
                new DownloadImageTask(mContentImage, null).execute(imgURL);
            } else {
                mContentImage.setVisibility(View.INVISIBLE);
            }
        }

        mNewsfeedDrawer.setVisibility(View.VISIBLE);
        if (!mNewsfeedDrawer.isOpened()) {
            mNewsfeedDrawer.animateOpen();
        }
    }

    private void initDetailViews() {
        CLog.i(TAG, "initDetailViews() E");

        if (mNewsfeedDrawer == null) {
            CLog.e(TAG, "initDetailViews() :: mNewsfeedDrawer is null");
            return;
        }

        if (mPrivatePicture == null) {
            mPrivatePicture = (ImageView) mNewsfeedDrawer.findViewById(R.id.private_picture);
        }

        mPrivatePicture.setImageBitmap(null);

        if (mPrivateName == null) {
            mPrivateName = (TextView) mNewsfeedDrawer.findViewById(R.id.private_name);
        }

        mPrivateName.setText(null);

        if (mPrivateDate == null) {
            mPrivateDate = (TextView) mNewsfeedDrawer.findViewById(R.id.private_date);
        }

        mPrivateDate.setText(null);

        if (mContentText == null) {
            mContentText = (TextView) mNewsfeedDrawer.findViewById(R.id.content_text);
        }

        mContentText.setText(null);

        if (mContentImage == null) {
            mContentImage = (ImageView) mNewsfeedDrawer.findViewById(R.id.content_image);
        }

        mContentImage.setImageBitmap(null);
    }

    public boolean keyUp(int keyCode, KeyEvent event) {
        boolean retVal = false;

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mNewsfeedDrawer.isOpened()) {
                mNewsfeedDrawer.animateClose();
                retVal = true;
            }
        }

        return retVal;
    }

    public void setNewsfeedData(FaceBookDataManager facebookdatamanager, MainCallBack feedViewScrollCallback) {
        CLog.i(TAG, "setNewsfeedData() E");

        // mFaceBookDataManager = FaceBookDataManager.getInstance();
        mFaceBookDataManager = facebookdatamanager;
        if (mFaceBookDataManager == null || feedViewScrollCallback == null) {
            CLog.e(TAG, "setNewsfeedData() :: facebookdatamanager is " + mFaceBookDataManager + "feedViewScrollCallback = " + feedViewScrollCallback);
            return;
        }

        mFeedDatas = mFaceBookDataManager.getFeedDataList();
        mProfileImageHash = mFaceBookDataManager.getProfileData();
        mFeedViewScrollCallback = feedViewScrollCallback;

        if (mNewsfeedList != null) {
            setFeedList();
        }
    }

    private String getTitle(int index) {
        String title = getFeedDataValue(index, Define.INDEX_MESSAGE);
        String story = getFeedDataValue(index, Define.INDEX_STORY);
        String name = getFeedDataValue(index, Define.INDEX_NAME);
        if (title != null) {
            return title;
        } else if (story != null) {
            return story;
        } else if (name != null) {
            return name;
        }

        return "";
    }

    private String getFeedDataValue(int index, String value) {
        if (mFeedDatas == null)
            return null;

        return mFeedDatas.get(index).getObject(value);
    }

    public void setFeedList() {
        CLog.i(TAG, "setFeedList Start");
        CLog.i(TAG, "mAdapter = " + mAdapter);

        if (null == mFeedDatas) {
            CLog.i(TAG, "mFeedDatas null");
            return;
        } else if (0 == mFeedDatas.size()) {
            return;
        }

        CLog.i(TAG, "mFeedDatas.size() = " + mFeedDatas.size());
        mNewsfeedContent.clear();
        for (int i = 0; i < mFeedDatas.size(); i++) {
            mNewsfeedContent.add(getTitle(i));
        }

        // mNewsfeedContent.addAll(Arrays.asList(tempString));
        if (null == mAdapter) {
            mAdapter = new NewsfeedListAdapter(getActivity(), R.layout.feedview_item);
            mNewsfeedList.setAdapter(mAdapter);
        } else {
            // TODO: next page
            mHandler.sendEmptyMessage(Define.FEEDVIEWFRAGMENT_ADAPTER_REFRESH);
        }
    }

    public void setFooterViewState(boolean state) {
        CLog.i(TAG, "setFooterViewState() :: state = " + state);
        mLoadingState = state;
        
        if (mHandler.hasMessages(Define.FEEDVIEWFRAGMENT_LOADING_STATE)) {
            mHandler.removeMessages(Define.FEEDVIEWFRAGMENT_LOADING_STATE);
        }
        
        mHandler.sendEmptyMessage(Define.FEEDVIEWFRAGMENT_LOADING_STATE);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        CLog.i(TAG, "onScroll() E");

        if (mFeedViewScrollCallback != null && mLoadingState) {
            mFeedViewScrollCallback.onScrollCallback(view, firstVisibleItem, visibleItemCount, totalItemCount);
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        CLog.i(TAG, "onScrollStateChanged() E");
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
